import { Card, message, Row, Col, Space } from 'antd';
import ProForm, {
  ProFormTextArea,
  ProFormSelect,
  ProFormDatePicker,
  ProFormDependency,
  ProFormText,
  ProFormRadio,
  ProFormDigit,
  ProFormUploadButton,
} from '@ant-design/pro-form';
import type { FC } from 'react';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import {
  addCase,
  queryNewCaseDetail,
  updateCaseNew,
  queryDiseaseClass,
  queryDoctor,
} from './servic';
import { queryUserVisitors } from '@/services/ant-design-pro/api';

const BasicForm: FC<Record<string, any>> = () => {
  const onFinish = async (values: Record<string, any>) => {
    console.log('onFinish', values);
    try {
      if (values.caseAuthorSelect) {
        values.caseAuthor = values.caseAuthorSelect.value;
        // values.doctorName = values.doctor.label;
        delete values.caseAuthorSelect;
      }
      if (values.symptomInfoImgsList.length > 0) {
        let filesUrl = '';
        for (var i = 0; i < values.symptomInfoImgsList.length; i++) {
          if (values.symptomInfoImgsList[0].response) {
            filesUrl += values.symptomInfoImgsList[i].response.data.url + '|';
          } else {
            filesUrl += values.symptomInfoImgsList[i].name + '|';
          }
        }
        values.symptomInfoImgs = filesUrl.substring(0, filesUrl.length - 1);
      }

      if (values.checkInfoImgsList.length > 0) {
        let filesUrl = '';
        for (var i = 0; i < values.checkInfoImgsList.length; i++) {
          if (values.checkInfoImgsList[0].response) {
            filesUrl += values.checkInfoImgsList[i].response.data.url + '|';
          } else {
            filesUrl += values.checkInfoImgsList[i].name + '|';
          }
        }
        values.checkInfoImgs = filesUrl.substring(0, filesUrl.length - 1);
      }

      if (values.diagnoseImgsList.length > 0) {
        let filesUrl = '';
        for (var i = 0; i < values.diagnoseImgsList.length; i++) {
          if (values.diagnoseImgsList[0].response) {
            filesUrl += values.diagnoseImgsList[i].response.data.url + '|';
          } else {
            filesUrl += values.diagnoseImgsList[i].name + '|';
          }
        }
        values.diagnoseImgs = filesUrl.substring(0, filesUrl.length - 1);
      }

      if (values.treatInfoImgsList.length > 0) {
        let filesUrl = '';
        for (var i = 0; i < values.treatInfoImgsList.length; i++) {
          if (values.treatInfoImgsList[0].response) {
            filesUrl += values.treatInfoImgsList[i].response.data.url + '|';
          } else {
            filesUrl += values.treatInfoImgsList[i].name + '|';
          }
        }
        values.treatInfoImgs = filesUrl.substring(0, filesUrl.length - 1);
      }

      if (values.prognosisInfoImgsList.length > 0) {
        let filesUrl = '';
        for (var i = 0; i < values.prognosisInfoImgsList.length; i++) {
          if (values.prognosisInfoImgsList[0].response) {
            filesUrl += values.prognosisInfoImgsList[i].response.data.url + '|';
          } else {
            filesUrl += values.prognosisInfoImgsList[i].name + '|';
          }
        }
        values.prognosisInfoImgs = filesUrl.substring(0, filesUrl.length - 1);
      }

      if (values.signInfoImgsList.length > 0) {
        let filesUrl = '';
        for (var i = 0; i < values.signInfoImgsList.length; i++) {
          if (values.signInfoImgsList[0].response) {
            filesUrl += values.signInfoImgsList[i].response.data.url + '|';
          } else {
            filesUrl += values.signInfoImgsList[i].name + '|';
          }
        }
        values.signInfoImgs = filesUrl.substring(0, filesUrl.length - 1);
      }
    } catch (e) {
      console.log('e', e);
    }
    console.log('values', values);

    if (history.location.query.id) {
      values.id = history.location.query.id;
      try {
        const response = await updateCaseNew(values);
        if (response.code == 200) {
          message.success('修改成功');
          history.push('/case/case-new-list');
        } else {
          message.error('修改失败!');
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      try {
        const response = await addCase(values);
        if (response.code == 200) {
          message.success('添加成功');
        } else {
          message.error('添加失败!');
        }
      } catch (error) {
        console.log(error);
      }
    }
  };

  const formItemLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 14 },
  };

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProForm
          hideRequiredMark
          style={{ margin: 'auto', marginTop: 8 }}
          name="basic"
          layout="horizontal"
          request={async () => {
            if (history.location.query.id) {
              return queryNewCaseDetail(history.location.query).then(({ data }) => {
                let doctor = {
                  value: data.doctorId,
                  label: data.doctorName,
                  key: data.doctorId,
                };
                data.doctor = doctor;

                let dept = {
                  value: data.deptId,
                  label: data.deptName,
                  key: data.deptId,
                };
                data.dept = dept;

                let hospital = {
                  value: data.hospitalId,
                  label: data.hospitalName,
                  key: data.hospitalId,
                };
                data.hospital = hospital;
                data.addUserType = data.addUserType + '';

                let listDiseaseList = [];
                for (var i = 0; i < data.listDisease.length; i++) {
                  let obj = {
                    value: data.listDisease[i].diseaseId,
                    label: data.listDisease[i].diseaseName,
                    key: data.listDisease[i].id,
                  };
                  listDiseaseList.push(obj);
                }

                data.listDiseaseList = listDiseaseList;

                let caseAuthorSelectName =
                  data.doctorName + ' ' + data.hospitalName + ' ' + data.deptName;
                let caseAuthorSelect = {
                  value: data.caseAuthor,
                  label: caseAuthorSelectName,
                  key: data.caseAuthor,
                };
                data.caseAuthorSelect = caseAuthorSelect;
                data.source = Number(data.source);
                data.patientType = Number(data.patientType);
                data.patientSex = Number(data.patientSex);
                console.log('data.symptomInfoImgs', data.symptomInfoImgs);
                if (data.symptomInfoImgs && data.symptomInfoImgs != '') {
                  let symptomInfoImgs = [];
                  let fileList = data.symptomInfoImgs.split('|');
                  for (var i = 0; i < fileList.length; i++) {
                    let obj = {
                      uid: i,
                      //name: 'symptomInfoImgs' + i,
                      name: fileList[i],
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + fileList[i],
                    };
                    symptomInfoImgs.push(obj);
                  }
                  data.symptomInfoImgsList = symptomInfoImgs;
                } else {
                  data.symptomInfoImgsList = [];
                }

                console.log('data.signInfoImgs', data.signInfoImgs);
                if (data.signInfoImgs && data.signInfoImgs != '') {
                  let signInfoImgs = [];
                  let fileList = data.signInfoImgs.split('|');
                  for (var i = 0; i < fileList.length; i++) {
                    let obj = {
                      uid: i,
                      // name: 'signInfoImgs' + i,
                      name: fileList[i],
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + fileList[i],
                    };
                    signInfoImgs.push(obj);
                  }
                  data.signInfoImgsList = signInfoImgs;
                } else {
                  data.signInfoImgsList = [];
                }
                console.log('data.checkInfoImgs', data.checkInfoImgs);
                if (data.checkInfoImgs && data.checkInfoImgs != '') {
                  let checkInfoImgs = [];
                  let fileList = data.checkInfoImgs.split('|');
                  for (var i = 0; i < fileList.length; i++) {
                    let obj = {
                      uid: i,
                      // name: 'checkInfoImgs' + i,
                      name: fileList[i],
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + fileList[i],
                    };
                    checkInfoImgs.push(obj);
                  }
                  data.checkInfoImgsList = checkInfoImgs;
                } else {
                  data.checkInfoImgsList = [];
                }

                console.log('data.diagnoseImgs', data.diagnoseImgs);
                if (data.diagnoseImgs && data.diagnoseImgs != '') {
                  let diagnoseImgs = [];
                  let fileList = data.diagnoseImgs.split('|');
                  for (var i = 0; i < fileList.length; i++) {
                    let obj = {
                      uid: i,
                      // name: 'diagnoseImgs' + i,
                      name: fileList[i],
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + fileList[i],
                    };
                    diagnoseImgs.push(obj);
                  }
                  data.diagnoseImgsList = diagnoseImgs;
                } else {
                  data.diagnoseImgsList = [];
                }
                console.log('data.treatInfoImgs', data.treatInfoImgs);
                if (data.treatInfoImgs && data.treatInfoImgs != '') {
                  let treatInfoImgs = [];
                  let fileList = data.treatInfoImgs.split('|');
                  for (var i = 0; i < fileList.length; i++) {
                    let obj = {
                      uid: i,
                      // name: 'treatInfoImgs' + i,
                      name: fileList[i],
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + fileList[i],
                    };
                    treatInfoImgs.push(obj);
                  }
                  data.treatInfoImgsList = treatInfoImgs;
                } else {
                  data.treatInfoImgsList = [];
                }
                console.log('data.prognosisInfoImgs', data.prognosisInfoImgs);
                if (data.prognosisInfoImgs && data.prognosisInfoImgs != '') {
                  let prognosisInfoImgs = [];
                  let fileList = data.prognosisInfoImgs.split('|');
                  for (var i = 0; i < fileList.length; i++) {
                    let obj = {
                      uid: i,
                      // name: 'prognosisInfoImgs' + i,
                      name: fileList[i],
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + fileList[i],
                    };
                    prognosisInfoImgs.push(obj);
                  }
                  data.prognosisInfoImgsList = prognosisInfoImgs;
                } else {
                  data.prognosisInfoImgsList = [];
                }

                console.log('data', data);
                return data;
              });
            } else {
              return { patientType: '0' };
            }
          }}
          onFinish={onFinish}
          {...formItemLayout}
          submitter={{
            render: (props, doms) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              );
            },
          }}
        >
          <Card bordered={false} title="病例信息">
            <ProFormText
              label="病例标题"
              name="caseTitle"
              width="md"
              rules={[
                {
                  required: true,
                  message: '请输入病例标题',
                },
              ]}
              placeholder="请输入病例标题"
            />
            <ProFormTextArea
              name="caseInfo"
              width="md"
              label="病例简介"
              placeholder="请输入病例简介"
            />
            <ProFormSelect
              width="md"
              name="listDiseaseList"
              label="病例标签"
              fieldProps={{
                labelInValue: true,
                mode: 'multiple',
              }}
              showSearch
              request={async ({}) => {
                let classId = 102;
                return queryDiseaseClass(classId).then(({ data }) => {
                  return data.map((item) => {
                    return {
                      label: item.name,
                      value: item.id,
                    };
                  });
                });
              }}
            />

            <ProFormSelect
              label="病例作者"
              name="caseAuthorSelect"
              width="md"
              rules={[
                {
                  required: true,
                  message: '请输入医生姓名或id',
                },
              ]}
              placeholder="请输入医生姓名或id"
              fieldProps={{
                labelInValue: true,
              }}
              showSearch
              request={async ({ keyWords }) => {
                if (keyWords != undefined && keyWords != '') {
                  return queryDoctor(keyWords).then(({ data }) => {
                    return data.map((item) => {
                      console.log(
                        'data',
                        item.name + ' ' + item.hospitalName + ' ' + item.firstDeptName,
                      );
                      return {
                        label: item.name + ' ' + item.hospitalName + ' ' + item.firstDeptName,
                        value: item.id,
                      };
                    });
                  });
                } else {
                  return [];
                }
              }}
            />
            <ProFormSelect
              width="md"
              name="source"
              label="病例来源"
              options={[
                {
                  value: 0,
                  label: '常规内容',
                },
                {
                  value: 1,
                  label: '病例大赛',
                },
              ]}
            />
          </Card>
          <Card bordered={false} title="患者信息">
            <ProFormRadio.Group
              options={[
                {
                  value: 0,
                  label: '实名',
                },
                {
                  value: 1,
                  label: '匿名',
                },
              ]}
              label="就诊人"
              name="patientType"
            />
            {/* <ProForm.Item label="" name="content"> */}
            <ProFormDependency name={['patientType']}>
              {({ patientType }) => {
                if (patientType == 0) {
                  return (
                    <ProFormSelect
                      width="md"
                      name="patientId"
                      label=" "
                      placeholder="请选择就诊人"
                      fieldProps={{
                        labelInValue: true,
                      }}
                      showSearch
                      request={async ({ keyWords }) => {
                        let query = {
                          likeQuery: {
                            visitor_name: keyWords,
                          },
                          pageNum: 1,
                          pageSize: 20,
                        };
                        return queryUserVisitors(query).then(({ data }) => {
                          return data.records.map((item) => {
                            return {
                              label: item.visitorName,
                              value: item.id,
                            };
                          });
                        });
                      }}
                    />
                  );
                } else {
                  return (
                    <div>
                      <ProFormDigit label="年龄" name="patientAge" width="md" min={1} max={100} />
                      <ProFormSelect
                        width="md"
                        name="patientSex"
                        label="性别"
                        options={[
                          {
                            value: 0,
                            label: '男',
                          },
                          {
                            value: 1,
                            label: '女',
                          },
                        ]}
                      />
                      <ProFormTextArea
                        name="pastHistory"
                        width="md"
                        label="既往史"
                        placeholder="请输入既往史"
                      />
                      <ProFormTextArea
                        name="familyHistory"
                        width="md"
                        label="家族史"
                        placeholder="请输入家族史"
                      />
                    </div>
                  );
                }
              }}
            </ProFormDependency>
            {/* </ProForm.Item> */}
            <ProFormDatePicker name="patientDate" label="就诊时间" width="md" />
            <ProFormText width="md" label="就诊医院" name="hospitalName" disabled />
            <ProFormTextArea name="symptomInfo" label="症状" placeholder="请输入症状" />
            <ProFormUploadButton
              name="symptomInfoImgsList"
              label="症状图片"
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/api/file/upload"
            />
            <ProFormTextArea name="signInfo" label="体征" placeholder="请输入体征" />
            <ProFormUploadButton
              name="signInfoImgsList"
              label="体征图片"
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/api/file/upload"
            />
            <ProFormTextArea name="checkInfo" label="检查" placeholder="请输入检查" />
            <ProFormUploadButton
              name="checkInfoImgsList"
              label="检查图片"
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/api/file/upload"
            />
            <ProFormTextArea name="diagnose" label="诊断" placeholder="请输入诊断" />
            <ProFormUploadButton
              name="diagnoseImgsList"
              label="诊断图片"
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/api/file/upload"
            />
            <ProFormTextArea name="treatInfo" label="治疗" placeholder="请输入治疗" />
            <ProFormUploadButton
              name="treatInfoImgsList"
              label="治疗图片"
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/api/file/upload"
            />
            <ProFormTextArea
              name="prognosisInfo"
              width="md"
              label="预后"
              placeholder="请输入预后"
            />
            <ProFormUploadButton
              name="prognosisInfoImgsList"
              label="预后图片"
              fieldProps={{
                name: 'file',
                listType: 'picture-card',
              }}
              action="/api/file/upload"
            />
          </Card>
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default BasicForm;
